﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ivy.Common.Framework.GeneralUtility;

using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.IBusinessLogic;
using Ivy.UserRegistration.BusinessLogic;

using Ivy.SiteAdmin.Entity;
using Ivy.SiteAdmin.IBusinessLogic;
using Ivy.SiteAdmin.BusinessLogic;

using DasIdeen.ViewEntity;

namespace DasIdeen.UserControls
{
    public partial class ContentFeedbackControl : System.Web.UI.UserControl
    {
        #region  Variable & constant
        string lContentCode = string.Empty;

        public AntiSpamUtility antiSpam = new AntiSpamUtility();
        #endregion  Variable & constant

        #region Constructor & Destructor
        #endregion Constructor & Destructor

        #region Properties
        public string ContentCode
        {
            get
            {
                return lContentCode;
            }
            set
            {
                lContentCode = value;

            }
        }
        #endregion Properties

        #region Public Methods
        public void LoadAllContentFeedback(string ContentCode)
        {
            try
            {
                this.ContentCode = ContentCode;
                List<ContentFeedbacks> lContentFeedback;
                SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                lContentFeedback = lSiteAdminContentManagementBus.GetSelectedContentFeedbackByContentCode(this.ContentCode);

                this.RptEstimationContentFeedback.DataSource = lContentFeedback;
                this.RptEstimationContentFeedback.DataBind();
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidCorrectAnswer.Value = antiSpam.GenerateMathFormula();
                lblAntiSpam.Text = antiSpam.MathFormula;
            }

            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    GetCurrentUser();
                    //TODO - Your code to display the initial layout/data etc.
                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnPostComment_Click(object sender, EventArgs e)
        {
            try
            {
                Int32 lContentFeedbackContentyKey = 1;
                Int32? lContentFeedbackFeedbackKey = null;
                Int32? lContentFeedbackUserKey = null;
                if (this.txtName.Text != "" && this.txtEmail.Text != "")
                {

                    if (this.ContentFeedbackEditor.Content != "")
                    {
                        if (this.txtAntiSpam.Text == hidCorrectAnswer.Value)
                        {
                            ContentFeedback lContentFeedback = new ContentFeedback();
                            SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();

                            //Mrinmoy - instead of passing hard coded contentkey value (which ia auto generated) get the actual key by passing the content code.
                            lContentFeedbackContentyKey = lSiteAdminContentManagementBus.GetSelectedContentMetaDataByContentCode(this.ContentCode).ContentKey;
                            lContentFeedback.ContentFeedbackContentKey = lContentFeedbackContentyKey;
                            lContentFeedback.ContentFeedbackFeedbackKey = Convert.ToInt32(lContentFeedbackFeedbackKey);
                            //Mrinmoy - All these codes are suppose to be in translate method
                            TranslateUIControlsToEntity(lContentFeedback);

                            //Mrinmoy - Error on foreignkey was due to the below statement. Based on the Email we need to internally get the userkey from user table by checking primary email ID, else it should be null;
                            User lUser;
                            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                            lUser = lUserRegistrationBus.GetUserByPrimaryEmailId(lContentFeedback.ContentFeedbackAuthorEmail);
                            if (lUser != null)
                            {
                                lContentFeedbackUserKey = lUser.UserKey;
                            }
                            lContentFeedback.ContentFeedbackAuthorUserKey = Convert.ToInt32(lContentFeedbackUserKey);

                            //Mrinmoy - the below statement it should be a user key and not user name, 
                            //that too only if the feedback is given by login user, if feedback is given by a guest user it will be -1;

                            //lContentFeedback.Sys_CreatedByID = this.txtName.Text;

                            //Default is guest user
                            lContentFeedback.Sys_CreatedByID = "-1";

                            UserContext tempUserSession = (UserContext)Session["UserContext"];
                            if (tempUserSession != null)
                            {
                                if (tempUserSession.CurrentUser != null)
                                {
                                    lContentFeedback.Sys_CreatedByID = tempUserSession.CurrentUser.UserKey.ToString();
                                }
                            }

                            lSiteAdminContentManagementBus.RegisterNewContentFeedback(lContentFeedback);
                            //Response.Redirect("~/Pages/ContentDetails.aspx");
                            ClearScreen();
                        }
                        else
                        {


                            hidCorrectAnswer.Value = antiSpam.GenerateMathFormula();
                            lblAntiSpam.Text = antiSpam.MathFormula;
                            this.lblAntiSpamErrorMessage.ForeColor = System.Drawing.Color.Red;
                            this.lblAntiSpamErrorMessage.Text = "Enter a vaild answer";
                            this.txtAntiSpam.Text = string.Empty;

                        }
                    }
                    else
                    {
                        this.lblMessageError.ForeColor = System.Drawing.Color.Red;
                        this.lblMessageError.Text = "Can't be blank,please give your valuable Message to us";
                        this.lblErrorMessage.Text = string.Empty;
                    }
                }
                else
                {

                    this.lblErrorMessage.ForeColor = System.Drawing.Color.Red;
                    this.lblErrorMessage.Text = "Can't be blank Name or Email id";
                    this.lblMessageError.Text = string.Empty;

                }
                

            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
            LoadAllContentFeedback(this.ContentCode);
        }
        #endregion Events

        #region Private Methods

        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }


        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
            this.txtName.Text = string.Empty;
            this.txtEmail.Text = string.Empty;
            this.ContentFeedbackEditor.Content = string.Empty;
            this.txtAntiSpam.Text = string.Empty;
            this.lblMessageError.Text = string.Empty;
            this.lblAntiSpamErrorMessage.Text = string.Empty;

        }

        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
        }


        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls()
        {
            User lUser = GetCurrentUser();
            this.txtName.Text = lUser.UserFirstName;
            this.txtEmail.Text = lUser.UserPrimaryEmailID;

        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToEntity(ContentFeedback pContentFeedback)
        {
            //pContentFeedback.ContentFeedbackContentKey = pContentFeedbackContentyKey;
            //pContentFeedback.ContentFeedbackFeedbackKey = Convert.ToInt32(pContentFeedbackContentyKey);
            pContentFeedback.ContentFeedbackText = this.ContentFeedbackEditor.Content;
            pContentFeedback.ContentFeedbackDate = DateTime.Now;
            User lUser = GetCurrentUser();
            if (lUser != null)
            {
                this.txtName.Text = lUser.UserFirstName;
                this.txtEmail.Text = lUser.UserPrimaryEmailID;
            }
            else
            {
                pContentFeedback.ContentFeedbackAuthorName = this.txtName.Text.Trim();
                pContentFeedback.ContentFeedbackAuthorEmail = this.txtEmail.Text.Trim();
            }
        }

        private User GetCurrentUser()
        {
            User UserKey = null;
            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    UserKey = tempUserSession.CurrentUser;
                    this.txtName.Text = tempUserSession.CurrentUser.UserFirstName;
                    this.txtEmail.Text = tempUserSession.CurrentUser.UserPrimaryEmailID;
                    this.txtName.ReadOnly = true;
                    this.txtEmail.ReadOnly = true;
                }
            }
            return UserKey;
        }
        #endregion Private Methods


    }
}